"""
认证相关 API
"""
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from datetime import timedelta
from app.core.database import get_db
from app.core.security import create_access_token, verify_password, hash_password
from app.core.config import settings
from app.schemas.user import UserLogin, LoginResponse, UserCreate, UserResponse
from app.schemas.common import ApiResponse
from app.models.user import User
from app.utils.helpers import generate_id

router = APIRouter()


@router.post("/login", response_model=ApiResponse[LoginResponse])
async def login(
    user_data: UserLogin,
    db: Session = Depends(get_db)
):
    """
    用户登录
    支持手机号+密码登录和微信code登录
    """
    user = None
    
    # 手机号密码登录
    if user_data.phone and user_data.password:
        user = db.query(User).filter(User.phone == user_data.phone).first()
        if not user or not verify_password(user_data.password, user.password_hash):
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="手机号或密码错误"
            )
    
    # 微信登录
    elif user_data.wechatCode:
        # 调用微信API获取 openid
        from app.services.wechat import wechat_service
        
        session_data = await wechat_service.code_to_session(user_data.wechatCode)
        if not session_data or not session_data.get("openid"):
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="微信登录失败，请重试"
            )
        
        openid = session_data["openid"]
        unionid = session_data.get("unionid")
        
        # 查找或创建用户
        user = db.query(User).filter(User.wechat_openid == openid).first()
        if not user:
            # 创建新用户
            user = User(
                id=generate_id(),
                nick_name=f"微信用户{generate_id()[:6]}",
                wechat_openid=openid,
                wechat_unionid=unionid,
                positions=[],
                team_ids=[],
                favorite_venues=[]
            )
            db.add(user)
            db.commit()
            db.refresh(user)
    
    else:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="请提供登录凭证"
        )
    
    # 生成 token
    access_token = create_access_token(
        data={"sub": user.id},
        expires_delta=timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    )
    
    return ApiResponse(
        data=LoginResponse(
            token=access_token,
            userInfo=UserResponse(**user.to_dict())
        )
    )


@router.post("/register", response_model=ApiResponse[LoginResponse])
async def register(
    user_data: UserCreate,
    db: Session = Depends(get_db)
):
    """
    用户注册（手机号）
    """
    # 检查手机号是否已注册
    if user_data.phone:
        existing_user = db.query(User).filter(User.phone == user_data.phone).first()
        if existing_user:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="该手机号已注册"
            )
    
    # 创建用户
    user = User(
        id=generate_id(),
        nick_name=user_data.nickName,
        avatar=user_data.avatar,
        phone=user_data.phone,
        password_hash=hash_password(user_data.password) if user_data.password else None,
        wechat_openid=user_data.wechatOpenid,
        positions=user_data.positions,
        city_id=user_data.cityId,
        city_name=user_data.cityName,
        team_ids=[],
        favorite_venues=[]
    )
    
    db.add(user)
    db.commit()
    db.refresh(user)
    
    # 生成 token
    access_token = create_access_token(
        data={"sub": user.id}
    )
    
    return ApiResponse(
        data=LoginResponse(
            token=access_token,
            userInfo=UserResponse(**user.to_dict())
        )
    )

